package com.qcby.service.impl;

import com.alibaba.fastjson.JSON;
import com.qcby.common.ClassNote.ShowByPage;
import com.qcby.dao.ClassNoteDao;
import com.qcby.dao.StudentExamDao;
import com.qcby.entity.*;
import com.qcby.service.ClassNoteService;
import com.qcby.util.DeepSeekUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class ClassNoteServiceImpl implements ClassNoteService {

    @Autowired
    ClassNoteDao classNoteDao;
    @Autowired
    DeepSeekUtils deepSeekUtils;
    @Autowired
    private StudentExamDao studentExamDao;
    @Override
    public Result<List<ClassNote>> showNoteInfoByPage(ShowByPage info) {
        info.setOffset((info.getPage() - 1) * info.getPageSize());
        return Result.success(classNoteDao.showNoteInfoByPage(info));
    }

    @Override
    public Result<Integer> getNoteCount(ShowByPage info) {
        return Result.success(classNoteDao.getNoteCount(info));
    }

    @Override
    public Result<ClassNote> addNote(ClassNote info) {
        if(classNoteDao.addNote(info) == 1){
            return Result.success(info);
        }else{
            return Result.error("添加笔记出错，请联系管理员!");
        }
    }

    @Override
    public Result<Integer> deleteNote(int id) {
        if(classNoteDao.deleteNote(id) == 1){
            return Result.success(id);
        } else{
            return Result.error("删除教案信息出错，请联系管理员！");
        }
    }

    @Override
    public Result<ClassNote> getNoteById(int id) {
        return Result.success(classNoteDao.getNoteById(id));
    }

    @Override
    public Result<ClassNote> updateNote(ClassNote info) {
        if(classNoteDao.updateNote(info) == 1){
            return Result.success(info);
        } else{
            return Result.error("修改笔记信息失败");
        }
    }
    @Override
    public List<ClassNote> getNoteByStudentName(Student student) {
        return classNoteDao.getNoteByStudentName(student);
    }
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public Result<Exam> addExam(ClassNote info) {
        Exam examInfo = new Exam();
        examInfo.setName(info.getName());
        examInfo.setCreator(info.getCreator());
        examInfo.setDuration(60);
        examInfo.setTotalScore(100);
        examInfo.setCreatetime(LocalDateTime.now());
        examInfo.setExamtime(LocalDateTime.now());
        examInfo.setStatus("进行中");
        StudentExam studentExam = new StudentExam();

        if(classNoteDao.addExam(examInfo) != 1){
            return Result.error("添加考试失败");
        }
        studentExam.setEid(examInfo.getId());
        studentExam.setStatus(examInfo.getStatus());
        studentExam.setSid(info.getSid());
        studentExamDao.insertStudentExam(studentExam);
        return Result.success(examInfo);
    }

    @Override
    public Result<Integer> generateQuestion(int e_id, String content) throws IOException {
        System.out.println(content);
        String prompt =
                "现在你需要模拟专业教师，根据以下笔记内容生成试题，严格遵循以下规则：\n" +
                        "---------------------------\n" +
                        "【笔记内容】\n" +
                        content + "\n" +
                        "---------------------------\n" +
                        "【生成规则】\n" +
                        "1. 题型仅包含：选择题、填空题、判断题、解答题、计算题（5种，严格按此枚举）\n" +
                        "2. 输出格式必须是JSON数组，每个题目字段要求：\n" +
                        "   - content: 题干内容（如“哪个城市属于中国？”）\n" +
                        "   - option: 仅选择题和判断题需要，选择题格式为[\"A.选项A\",\"B.选项B\",\"C.选项C\",\"D.选项D\"]判断题格式为[\"正确\",\"错误\"]（其他题型填空字符串\"\"）\n" +
                        "   - score: 分值规则（选择题/判断题:2分；填空题:5分；解答题/计算题:10分）\n" +
                        "   - type: 题型（严格匹配：选择题、填空题、判断题、解答题、计算题）\n" +
                        "3. 示例（可直接参考结构）：\n" +
                        "   [\n" +
                        "     {\"content\": \"哪个城市属于中国？\", \"option\": [\"A.北京\",\"B.伦敦\",\"C.纽约\",\"D.巴黎\"], \"score\": 2, \"type\": \"选择题\"},\n" +
                        "     {\"content\": \"中国首都是______\", \"option\": \"\", \"score\": 5, \"type\": \"填空题\"},\n" +
                        "     {\"content\": \"伦敦属于中国吗？\", \"option\": [\"正确\",\"错误\"], \"score\": 2, \"type\": \"判断题\"},\n" +
                        "     {\"content\": \"简述中国首都的历史意义\", \"option\": \"\", \"score\": 10, \"type\": \"解答题\"}\n" +
                        "   ]\n" +
                        "4. 所有题目必须覆盖笔记核心知识点，难度适中\n" +
                        "5. 严格按JSON格式输出，不要额外注释或说明，直接返回可解析的JSON数组！" +
                        "6. 题干和选项中若包含数学公式，用纯文本描述（例如“极限 lim(x→0) sinx/x”，而非带反斜杠的格式），避免使用特殊符号。\n" +
                        "7. JSON中的键名必须使用未转义的双引号，如\"content\"，不能出现\\\"content\\\"这样的格式。8.题目的总数为10~20道，总分是100分，严格满足";

        String questionsJson = deepSeekUtils.askAi(prompt);
        System.out.println("AI原始响应: " + questionsJson);

        String cleanedJson = questionsJson
                .replace("```json", "")  // 移除JSON代码块标记
                .replace("```", "")      // 移除剩余的反引号
                .replace("\\\"", "\"")   // 取消引号转义
                .replace("\\\\", "\\")   // 取消反斜杠转义
                .replace("\n", " ")      // 换行符替换为空格
                .replace("\r", "")       // 移除回车符
                .trim();                 // 去除首尾空白

// 确保是合法的JSON数组格式
        if (!cleanedJson.startsWith("[")) {
            cleanedJson = "[" + cleanedJson;
        }
        if (!cleanedJson.endsWith("]")) {
            cleanedJson = cleanedJson + "]";
        }

// 移除可能残留的非JSON内容
        cleanedJson = cleanedJson.replaceAll("^[^\\[]*", "").replaceAll("[^\\]]*$", "");

        System.out.println("处理后的JSON: " + cleanedJson);

        List<QuestionBank> questionList = JSON.parseArray(cleanedJson, QuestionBank.class);

        for (QuestionBank question : questionList) {
            question.setE_id(e_id);
        }

        int count = classNoteDao.addQuestion(questionList);
        return Result.success(count);
    }

}
